<template>
  <div class="main">
    <InputSearch
      v-model:value="searchValue"
      placeholder="请输入要查询的组织"
      class="input_search"
      @search="onSelectOrg"
      style="margin-right: 80px"
    ></InputSearch>
    <Tree
      class="tree"
      :expandedKeys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :tree-data="gData"
      :fieldNames="replaceFields"
      @expand="onExpand"
      @select="onSelect"
      show-line
    >
      <template #title="{ name }">
        <span v-if="name.indexOf(searchValue) > -1">
          {{ name.substr(0, name.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
        </span>
        <span v-else>{{ name }}</span>
      </template>
    </Tree>
  </div>
</template>
<script setup lang="ts">
import { InputSearch, Tree } from 'ant-design-vue';
import { ref } from 'vue';
import { getSaaSOrgTree } from '/@/api/organization-mgmt/organization';

const searchValue = ref('');
const expandedKeys = ref<string[]>([]);
const autoExpandParent = ref<boolean>(true);
const gData = ref<any[]>([]);
let dataList: any[] = [];
const replaceFields = {
  children: 'children',
  title: 'name',
  key: 'id',
};
const emit = defineEmits(['selectOrg']);
async function fetchOrgTree() {
  dataList = await getSaaSOrgTree();
  gData.value = dataList;
  if (dataList && dataList[0] && dataList[0].id) {
    emit('selectOrg', { id: dataList[0].id });
  }
}

fetchOrgTree();

const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

const onSelect = (key: string[]) => {
  emit('selectOrg', { id: key[0] });
};
function mapTree(arr: [], value: string) {
  let newarr = [];
  for (let element of arr) {
    if (element.name.includes(value)) {
      // 判断条件
      newarr.push(element);
      expandedKeys.value.push(element.id);
    } else {
      if (element.children && element.children.length > 0) {
        let redata = mapTree(element.children, value);
        if (redata && redata.length > 0) {
          let obj = {
            ...element,
            children: redata,
          };
          newarr.push(obj);
        }
      }
    }
  }
  return newarr;
}
function onSelectOrg() {
  if (searchValue.value) {
    gData.value = mapTree(dataList, searchValue.value);
  } else {
    gData.value = dataList;
  }
  autoExpandParent.value = true;
}
</script>
<style lang="less">
.main {
  height: 100%;
  .tree {
    margin-top: 20px;
  }
}
</style>
